import config from "@/config";
import {post} from "@/utils/request";
import {eachTree, listToTree} from "@/utils/utils";
import {PermissionModel} from "@/pages/sys/role/data";
import React from "react";
import {ApiResult, TreeNodeModel} from "@/global";

/** 获取系统账户权限接口基地址 */
const getUrl = (url: string) => config.apiBaseUrl + '/sys/permission' + url;

const DeptScopeEnum = {
  All:"全部",

  /** 自定义 */
  Custom :"自定义",

  /** 所在部门及所有下级 */
  DeptAndLower:"所在部门及所有下级",

  /** 所在部门 */
  Dept:"所在部门",

  /** 仅本人 */
  User:"仅本人",
}


/** 系统账户权限接口 */
const service = {
  /** 转换Tree节点属性 */
  convertTreeNode(obj:any) {
    obj['title'] =obj.name;
    obj['key'] = obj.id;
    obj['icon'] = (<i className={obj.webCls}/>);
  },

  /** 查询用户功能权限 */
  async selectUserPermissionModules(id:string|undefined):Promise<ApiResult<[]>> {
    return post(getUrl( '/selectUserPermission'), {userId:id}).then((r: any) => {
      const treeData = listToTree(r.data.modules, service.convertTreeNode);
      return {code:0,success: true, data: treeData as []};
    });
  },

  /** 查询用户功能权限 */
  async selectUserPermissionDept(id:string|undefined){
    return post(getUrl('/selectUserPermission'),{userId:id}).then((r: any) => {
      const treeData=listToTree(r.data.deptScopePermission.customs?r.data.deptScopePermission.customs:[],service.convertTreeNode);
      eachTree(treeData,obj=>{
        obj['icon'] =(<i className={obj.children==undefined?'fa fa-flag':'fa fa-folder'}/>);
      });
      return {
        code:0,
        success: true,
        data: { deptScope: DeptScopeEnum[r.data.deptScopePermission.deptScope],
          data:treeData}
      };
    });
  },

  /** 系统角色授权 */
  async saveRolePermission(params: PermissionModel){
    return post(getUrl( '/saveRolePermission'), params);
  },

  /** 查询角色权限列表 */
  async selectRolePermission(id:string|undefined){
    return post(getUrl( '/selectRolePermission'), {roleId:id});
  },

  /** 查询角色拥有的模块权限 */
  async selectRoleModule(id:string|undefined){
    return post(getUrl( '/selectRolePermission'), {roleId:id}).then((r: any) => {
      const treeData = listToTree(r.data.modules, service.convertTreeNode);
      return {code:0,success: true, data: treeData};
    });
  },

  /** 系统角色拥有的部门权限 */
  async saveRoleDept(id:string|undefined):Promise<ApiResult<{deptScope:any,data:TreeNodeModel[]}>>{
    return post(getUrl( '/selectRolePermission'), {roleId:id}).then((r: any) => {
      const treeData = listToTree(r.data.deptScopePermission.customs?r.data.deptScopePermission.customs:[],service.convertTreeNode);
      eachTree(treeData,obj=>{
        obj['icon'] =(<i className={obj.children==undefined?'fa fa-flag':'fa fa-folder'}/>);
      });
      return {code:0,success: true, data:{deptScope: DeptScopeEnum[r.data.deptScopePermission.deptScope],data:treeData} };
    });
  },
}


export default service;
